<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Birthday
 *
 * @author user2
 */
class Bluembo_Validate_Birthday extends Zend_Validate_Date {

    private $_dateOfBirth;

    const MIN_AGE  = 13;
    const MIN_YEAR = 1900;

    public function isValid($value)
    {
        if (!parent::isValid($value)) {
            return false;
        }
        $age = $this->getAge($value);
        
        if ($age < self::MIN_AGE && $this->_dateOfBirth->toValue('Y') <= $this->_dateOfBirth->now()->toValue('Y')) {
            $message = sprintf("%s %s %s",_("You should be"),self::MIN_AGE,_("years old."));
            $this->setMessage($message, self::INVALID_DATE);
            $this->_error(self::INVALID_DATE);
            return false;
        } elseif ($this->_dateOfBirth->toValue('y') < self::MIN_YEAR || $this->_dateOfBirth->toValue('Y') > $this->_dateOfBirth->now()->toValue('Y')) {
            $this->_error(self::INVALID_DATE);
            return false;
        }
        return true;
    }

    public function getAge($value)
    {
        $today = new Zend_Date();
        $this->_dateOfBirth = new Zend_Date($value, $this->getFormat(), $this->getLocale());
        $age   = $today->subYear($this->_dateOfBirth)->toValue('y');
        if ($today->toString('D') < $this->_dateOfBirth->toString('D')) {
            $age--;
        }
        return $age;
    }

}
